import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios';

export const useSimulationStore = defineStore('simulation', () => {
    let year = 2019
    let month = 5
    let date = 14
    // 时间模拟相关状态
    const initialTime = ref(new Date(year,month,date))
    const currentTime = ref(new Date(year,month,date))
    const timeSpeed = ref({
        speed_description: "1s/s",
        speed_value: 1,
        real_time: 1000
    })
    const isSimulating = ref(false)
    const isPaused = ref(false)
    let timer: number | null = null

    // 格式化时间显示
    const formattedTime = computed(() => formatDateTime(currentTime.value))

    // 格式化日期时间
    const formatDateTime = (date: Date) => {
        const pad = (num: number) => num.toString().padStart(2, '0')
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
    }

    // 获取日志数据
    const fetchLogs = async (time: string) => {
        // try {
        //     const response = await fetch(`http://localhost:5000/api/logs?time=${time}`)
        //     const data = await response.json()
        //     if (Array.isArray(data)) {
        //         logCache.value = [...logCache.value, ...data]
        //         // 触发日志处理
        //         data.forEach(log => processLogEntry(log))
        //     }
        // } catch (error) {
        //     console.error('获取日志失败:', error)
        // }
    }

    // 开始模拟
    const startSimulation = async() => {
        if (isSimulating.value) return
        isSimulating.value = true
        currentTime.value = new Date(initialTime.value)
        // const response = await axios.post('http://localhost:5000/api/reset');
        // if (response.status === 200) {
        //     await updateTime()
        // }
        await updateTime()
    }

    // 停止模拟
    const stopSimulation = () => {
        isSimulating.value = false
        isPaused.value = false
        if (timer) {
            clearTimeout(timer)
            timer = null
        }
    }

    // 重置模拟
    const resetSimulation = () => {
        stopSimulation()
        initialTime.value = new Date(year,month,date)
        currentTime.value = new Date(year,month,date)
        timeSpeed.value = {
            speed_description: "1s/s",
            speed_value: 1,
            real_time: 1000
        }
    }

    // 更新时间
    const updateTime = async () => {
        if (!isSimulating.value || isPaused.value) return

        const now = new Date(currentTime.value)
        now.setSeconds(now.getSeconds() + timeSpeed.value.speed_value)
        currentTime.value = now

        // 获取当前时间的日志
        await fetchLogs(formattedTime.value)

        // 更新时间间隔根据速度调整
        const interval = timeSpeed.value.real_time
        timer = setTimeout(updateTime, interval);
    }

    // 暂停/继续模拟
    const togglePause = async() => {
        isPaused.value = !isPaused.value

        if (!isPaused.value) {
            // 继续模拟
            await updateTime()
        } else {
            // 暂停模拟
            if (timer) {
                clearTimeout(timer)
                timer = null
            }
        }
    }

    return {
        initialTime,
        currentTime,
        formattedTime,
        timeSpeed,
        isSimulating,
        isPaused,
        startSimulation,
        stopSimulation,
        resetSimulation,
        updateTime,
        togglePause,
        formatDateTime
    }
})